package com.litchi.activity;

import java.text.SimpleDateFormat;
import java.util.Date;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.litchi.R;
import com.litchi.app.SysApplication;
import com.litchi.dialogfragment.CacheDialogFragment;
import com.litchi.dialogfragment.ExitDialogFragment;
import com.litchi.utils.CacheUtils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MoreActivity extends FragmentActivity implements OnClickListener,AMapLocationListener{
 	private TextView mTvCacheSize;
	private SeekBar mSeekBarBrightness;
	private View mViewNightMode;
	private ToggleButton mTgLight;
	private static Context mContext;
 	private TextView cityTextView;
 	 
 	//声明AMapLocationClient类对象
 	public AMapLocationClient mLocationClient = null;
 	//声明mLocationOption对象
 	public AMapLocationClientOption mLocationOption = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SysApplication.getInstance().addActivity(this);
		setContentView(R.layout.activity_more);
		mContext = this;
		 
		//初始化定位
	 	mLocationClient = new AMapLocationClient(getApplicationContext());
	 	//设置定位回调监听
	 	mLocationClient.setLocationListener(this);
	 	
		cityTextView = (TextView) findViewById(R.id.location_city);
	 
		mViewNightMode = findViewById(R.id.layout_night_mode);
		mTvCacheSize = (TextView) findViewById(R.id.tv_cache_size);
		mSeekBarBrightness = (SeekBar) findViewById(R.id.seekBar_light);
		mTgLight = (ToggleButton) findViewById(R.id.tgbtn_lightness_ctrl);
		findViewById(R.id.layout_location).setOnClickListener(this);
		findViewById(R.id.img_back).setOnClickListener(this);
		findViewById(R.id.layout_about).setOnClickListener(this);
		findViewById(R.id.layout_clear_cache).setOnClickListener(this);
		findViewById(R.id.layout_recom_apps).setOnClickListener(this);
		findViewById(R.id.btn_logout).setOnClickListener(this);
		mTgLight.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					mViewNightMode.setVisibility(View.VISIBLE);
					initBrightness();
				} else {
					mViewNightMode.setVisibility(View.GONE);

					// 或去当前系统亮度
					int tmpInt = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, -1);
					WindowManager.LayoutParams wl = getWindow().getAttributes();
					float tmpFloat = (float) tmpInt / 255;
					if (tmpFloat > 0 && tmpFloat <= 1) {
						wl.screenBrightness = tmpFloat;
					}
					getWindow().setAttributes(wl);

				}
			}
		});
		initCacheSize();
		 
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		//初始化定位参数
		mLocationOption = new AMapLocationClientOption();
		//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
		mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
		//设置是否返回地址信息（默认返回地址信息）
		mLocationOption.setNeedAddress(true);
		//设置是否只定位一次,默认为false
		mLocationOption.setOnceLocation(false);
		//设置是否强制刷新WIFI，默认为强制刷新
		mLocationOption.setWifiActiveScan(true);
		//设置是否允许模拟位置,默认为false，不允许模拟位置
		mLocationOption.setMockEnable(false);
		//设置定位间隔,单位毫秒,默认为2000ms
		mLocationOption.setInterval(2000);
		//给定位客户端对象设置定位参数
		mLocationClient.setLocationOption(mLocationOption);
		//启动定位
		mLocationClient.startLocation();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mLocationClient.onDestroy();//销毁定位客户端。
	}

	/**
	 * 获取缓存大小
	 */
	private void initCacheSize() {
		String cacheSize = CacheUtils.getCacheSize(this);
		mTvCacheSize.setText(cacheSize);
	}

	/**
	 * 亮度调节
	 */
	private void initBrightness() {
		// 取得当前亮度
		int normal = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, 255);
		// 进度条绑定当前亮度
		mSeekBarBrightness.setProgress(normal);
		mSeekBarBrightness.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// 取得当前进度
				int tmpInt = seekBar.getProgress();

				// 当进度小于80时，设置成80，防止太黑看不见的后果。
				if (tmpInt < 80) {
					tmpInt = 80;
				}
				// 根据当前进度改变亮度
				WindowManager.LayoutParams wl = getWindow().getAttributes();
				float tmpFloat = (float) tmpInt / 255;
				if (tmpFloat > 0 && tmpFloat <= 1) {
					wl.screenBrightness = tmpFloat;
				}
				getWindow().setAttributes(wl);
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_back:// 返回
			finish();
			break;
		case R.id.layout_location:// 设置位置
//			startActivity(new Intent(this, LocationActivity.class));
			 
			break;
		case R.id.layout_about: // 关于
			startActivity(new Intent(this, AboutActivity.class));
			break;
		case R.id.layout_clear_cache: // 清除缓存
			clearCache();
			break;
		case R.id.layout_recom_apps: // 应用推荐
			startActivity(new Intent(this, DownloadActivity.class));
			break;
		case R.id.btn_logout: // 注销
			// LogoutDialogFragment fragment = new LogoutDialogFragment();
			// fragment.show(getSupportFragmentManager(), null);

			ExitDialogFragment fragment = new ExitDialogFragment();
			fragment.show(getSupportFragmentManager(), null);

			break;

		default:
			break;
		}
	}

	/**
	 * 清除缓存
	 */
	private void clearCache() {
		CacheDialogFragment cacheDialogFragment = new CacheDialogFragment();
		cacheDialogFragment.setTextView(mTvCacheSize);
		cacheDialogFragment.show(getSupportFragmentManager(), null);
	}
	 

	@SuppressLint("SimpleDateFormat")
	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		// TODO Auto-generated method stub
		if (amapLocation != null) {
	        if (amapLocation.getErrorCode() == 0) {
	        //定位成功回调信息，设置相关消息
	        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
	        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        Date date = new Date(amapLocation.getTime());
	        df.format(date);//定位时间
	        
	                cityTextView.setText("更新于"+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()+amapLocation.getCountry()+amapLocation.getProvince()+amapLocation.getCity()+amapLocation.getDistrict()+amapLocation.getStreet()+amapLocation.getStreetNum());
	                mLocationClient.stopLocation();//停止定位
	        } else {
	              //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
	        	cityTextView.setText("未知");
	        Log.e("AmapError","location Error, ErrCode:"
	            + amapLocation.getErrorCode() + ", errInfo:"
	            + amapLocation.getErrorInfo());
	        }
	    }
	}

	 
}
